#!/usr/bin/python
# -*- coding: utf-8 -*-

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *

__version__ = "0.1 (Adva)"

import sys, os
import re
import mailcap, mimetypes

UNREAD_EXTRACTOR = re.compile(r"[^\(]+\((?P<unread>\d+)\)")
SAFARI_USER_AGENT  = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-us) AppleWebKit/531.9 (KHTML, like Gecko) Version/4.0.3 Safari/531.9"
BASE_URL = "https://wave.google.com/wave/"
START_URL = "http://wave.google.com"
LOGO_FILE = "google_wave_logo.png"

def runUrl(url):
	mimetype = mimetypes.guess_type(url)[0]
	# Assume html
	if mimetype == None: 
		mimetype = "text/html"
	d = mailcap.getcaps()
	os.system(mailcap.findmatch(d, mimetype, filename = url)[0])
	
class ImpersonatorWebPage(QWebPage):
	def __init__(self, parent = None):
		QWebPage.__init__(self, parent)
		self.userAgent = "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543 Safari/419.3"
	
	def userAgentForUrl(self, url):
		return self.userAgent
	
class Tsunami(QMainWindow):
	def __init__(self, parent = None):
		QMainWindow.__init__(self, parent)
		self.mainView = QWebView(self)
		self.impersonator = ImpersonatorWebPage()
		# We need to lie so wave wouldn't bother us with competability. Safari is the colsest match because we both use WebKit and don't have gears
		self.impersonator.userAgent = SAFARI_USER_AGENT
		self.impersonator.setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
		
		self.mainView.setPage(self.impersonator)
		self.setCentralWidget(self.mainView)
		self.mainView.setUrl(QUrl(START_URL))
		self.baseIcon = QPixmap(LOGO_FILE)
		
		self.setWindowTitle("Tsunami - %(version)s" % {"version" : __version__})
		self.setWindowIcon(QIcon(self.baseIcon))		
		
		self.tray = QSystemTrayIcon(QIcon(self.baseIcon), self)
		self.tray.setVisible(True)
		
		self.trayFont = QFont("Helvetica [Cronyx]", 125)
		self.trayFont.setBold(True)
		
		self.connect(self.tray, SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self.trayClicked)
		self.connect(self.impersonator.mainFrame(), SIGNAL("titleChanged(QString)"), self.updateUnread)
		self.connect(self.impersonator, SIGNAL("linkClicked(QUrl)"), self.testJail)
		self.lastUnreadStatus = 0
	
	def testJail(self, url):
		urls = unicode(url.toString())
		if urls.startswith(BASE_URL):
			self.mainView.setUrl(url)
			return
		runUrl(urls)
		
	def trayClicked(self, reason):
		if reason == QSystemTrayIcon.Trigger:
			if self.isVisible():
				self.oldGeometry = self.saveGeometry()
				self.setVisible(False)
			else:
				self.setVisible(True)
				self.restoreGeometry(self.oldGeometry)
			
	def updateUnread(self, titleString):
		res = UNREAD_EXTRACTOR.search(unicode(titleString))
		if res == None:
			self.tray.setIcon(QIcon(self.baseIcon))
			self.lastUnreadStatus = 0
			return
			
		unreadNum = int(res.groupdict()["unread"])
		if unreadNum > self.lastUnreadStatus:
			self.tray.showMessage("You have more unread waves!", "You have %d unread waves." % (unreadNum))
		self.lastUnreadStatus = unreadNum
		
		self.tray.setIcon(self.getUnreadTrayIcon(unreadNum))
		
	def getUnreadTrayIcon(self, unreadNum):
		tmpImg = self.baseIcon.copy()
		imgWidth = tmpImg.width()
		imgHeight = tmpImg.height()
		
		pen = QPen(Qt.black)
		pen.setWidth(10)
		brush = QBrush(Qt.white)
		
		path = QPainterPath()
		path.addText(QPointF(0, 0), self.trayFont ,unicode(unreadNum))
		pathWidth = path.boundingRect().width()
		pathHeight = path.boundingRect().height()
		painter = QPainter(tmpImg)
		painter.setPen(pen)
		painter.setBrush(brush)
		painter.translate( (imgWidth - pathWidth) / 2,(imgHeight + pathHeight) / 2)
		painter.drawPath(path)
		painter.end()
		return QIcon(tmpImg)
def main():
	app = QApplication(sys.argv)
	main = Tsunami()
	main.show()
	app.exec_()

if __name__ == "__main__":
	main()